<?php
error_reporting(E_ALL);

require_once(dirname(__FILE__) . '/lib/curl.class.php');
require_once(dirname(__FILE__) . '/lib/phpQuery/phpQuery.php');


class Moodle {
  private $userAgent;
  private $baseUri;
  private $debugLevel = 0;
  private $currentPage;
  private $lastError;

  public function __construct($baseUri){
    $this->userAgent = new CURL();
    $this->userAgent->setHTTPVersion('1.0');
    $this->userAgent->debugLevel($this->debugLevel);
    
    $this->baseUri = $baseUri;
    $this->currentPage = '';
    $this->lastError = '';
  }

  public function __destruct(){
    $this->userAgent->close();
  }

  public function login($user, $pass){
    $this->currentPage = $this->userAgent->get($this->baseUri);
    $theForm = CURL::getMatched('|<form[^>]*id="login">.*?</form>|si', $this->currentPage, 0);

    $form = CURL::readFormFields($theForm, & $formAction);

    $form['username'] = $user;
    $form['password'] = $pass;
    $this->currentPage = $this->userAgent->post($formAction, $form);

    $message = CURL::getMatched('|<span class="error">(.*?)</span>|si', $this->currentPage, 1);
    if(! empty($message)){
      $this->lastError = utf8_decode($message);
      return false;
    }

    return true;
  }

  public function lastErrorMessage(){
    return $this->lastError;
  }

  public function getCourseList(){
    $doc = phpQuery::newDocument($this->currentPage);    

    $coursesLink = $doc->find('div.block_course_list ul.list > li > div.c1 > a');

    $list = array();
    foreach($coursesLink as $courseLink){
      $name = _utf8_decode($courseLink->nodeValue);

      printf("%s = %s => %s\n", $courseLink->getAttribute('title'), $name, $courseLink->getAttribute('href')) ;
      $list[] = $courseLink->nodeValue;
    }
    return $list;
  }
  
} //end class Moodle

function _utf8_decode($string){
  $tmp = $string;
  $count = 0;
  while (mb_detect_encoding($tmp)=="UTF-8"){
    $tmp = utf8_decode($tmp);
    $count++;
  }
 
  for ($i = 0; $i < $count-1 ; $i++){
    $string = utf8_decode($string);  
  }
  return $string; 
}

if($argc != 4){
  die(sprintf("Usage: %s <url> <user> <password>\n", basename($argv[0])));
}
list($program, $url, $user, $password) = $argv;

$moodle = new Moodle($url);

if($moodle->login($user, $password)){
  $courses = $moodle->getCourseList();
}else{
  echo $moodle->lastErrorMessage(), "\n";
}
?>
